#Author: Dina Helal

from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json
import base64

#Get Location coordinates of a certain restaurant given its key 
class Location(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        self.response.headers['Content-Type'] = 'text/plain'
        q=db.get(id);    
        result = [[{'latitude': q.locationLong}], [{'longitude': q.locationLat}],{'name': str(q.name)}]
        self.response.out.write(json.dumps(result))
        
class DishImg(webapp.RequestHandler):
    def get(self):
        id = self.request.get('id')
        self.response.headers['Content-Type'] = 'text/plain'
        q=db.get(id);    
        result = [{'img': base64.b64encode(q.img)}]
        self.response.out.write(json.dumps(result))


class Edit(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("in GET");
        
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        restaurantName = self.request.get("restaurantName");
        longitudesString = self.request.get("longitudes");
        latitudesString = self.request.get("latitudes");
        
        longitudes = []
        longitudesSplit = longitudesString.split('#');
        for longitude in longitudesSplit:
            longitudes.append(float(longitude)); 

        latitudes = []
        latitudesSplit = latitudesString.split('#');          
        for latitude in latitudesSplit:
            latitudes.append(float(latitude));
        
        query = db.GqlQuery("SELECT * FROM Restaurant WHERE name = :1 LIMIT 1", restaurantName);
        dishRestaurant = query[0];
        dishRestaurant.locationLong.extend(longitudes);
        dishRestaurant.locationLat.extend(latitudes);
        dishRestaurant.put();
        
application = webapp.WSGIApplication([('/location', Location), ('/dish_img', DishImg), ('/edit',Edit)], debug=True)
  
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
